package com.tigercel.xiangchengyun.ui.fragments


import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.GridView
import android.widget.LinearLayout
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.adapter.*
import com.tigercel.xiangchengyun.entity.Banner
import com.tigercel.xiangchengyun.entity.ProdctBean
import com.tigercel.xiangchengyun.entity.TopNewsEntity
import com.tigercel.xiangchengyun.ui.activities.LivePlayActivity
import com.tigercel.xiangchengyun.ui.activities.SearchActivity
import com.tigercel.xiangchengyun.ui.activities.WebViewActivity
import com.tigercel.xiangchengyun.ui.custom.lbanners.LMBanners
import com.tigercel.xiangchengyun.ui.custom.lbanners.transformer.TransitionEffect
import com.tigercel.xiangchengyun.ui.custom.lbanners.utils.ScreenUtils
import com.tigercel.xiangchengyun.utils.ExpandListView
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.fragment_recommend.*
import org.jetbrains.anko.support.v4.toast

class RecommendFragment : Fragment() {
    private var channelPosition: Int = 0
    private var headBanner: View? = null
    private var headServices: View? = null
    private var topNews: View? = null
    private var youlikeNews: View? = null
    private var freelifeNews: View? = null
    private var proName = ArrayList<String>()
    private var proId = ArrayList<String>()
    private var proType = ArrayList<String>()
    private var proUrl = ArrayList<String>()
    private var proIcon = ArrayList<String>()
    private var listAdapter: TopNewAdapter? = null
    private var listviewtop: ExpandListView? = null
    private var listviewyoulike: ExpandListView? = null
    private var listviewfreelife: ExpandListView? = null
    private var totalPage: Int = 1 //总的页数，默认1页
    private var mPageSize: Int = 8 //每页显示的最大的数量
    private lateinit var listDatas: MutableList<ProdctBean>
    private lateinit var viewPagerList: MutableList<View>
    private var mIndicatorWidth = 7//默认指示器大小
    private var mSelectIndicatorRes = R.drawable.page_indicator_select//选中指示器
    private var mUnSelectIndicatorRes = R.drawable.page_indicator_unselect//未选中指示器
    private var pageItemWidth: Int = 0
    private var viewPager: ViewPager? = null
    private var indicatorLayout: LinearLayout? = null
    private var banner: LMBanners<Any>? = null

    private val ACTION_REFRESH = 1
    private val ACTION_LOAD_MORE = 2
    private var mCurrentAction = ACTION_REFRESH
    private var mCurrentPageIndex = 1
    private var runtimes = 1
    private lateinit var newsAdapter: NewsAdapter
    private var topentitylist: MutableList<TopNewsEntity> = ArrayList()
    private var youlikeentitylist: MutableList<TopNewsEntity> = ArrayList()
    private var freelifeentitylist: MutableList<TopNewsEntity> = ArrayList()
    private var localDatas: PreferencesUtil? = null
//    private var banners: MutableList<Banner>

    companion object {

        fun newInstance(channelPosition: Int): RecommendFragment? {

            val fragment = RecommendFragment()
            val bundle = Bundle()
            bundle.putInt("channelPosition", channelPosition)
            fragment.arguments = bundle
            return fragment
        }
    }


    private var containerView: View? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        containerView = inflater.inflate(R.layout.fragment_recommend, container, false)
        if (arguments != null)
            channelPosition = arguments!!.getInt("channelPosition")
        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        searchLayout.setOnClickListener({ startActivity(Intent(activity, SearchActivity::class.java)) })
        recyclerview.layoutManager = LinearLayoutManager(activity)
        newsAdapter = NewsAdapter(ArrayList()) {}
        recyclerview.adapter = newsAdapter
        headBanner = View.inflate(activity, R.layout.banners, null)
        banner = headBanner?.findViewById(R.id.banners)
        banner!!.setIndicatorBottomPadding(8)
        banner!!.setHoriZontalTransitionEffect(TransitionEffect.Default)

        headServices = View.inflate(activity, R.layout.grid_service_layout, null)
        viewPager = headServices?.findViewById(R.id.viewpager)
        indicatorLayout = headServices?.findViewById(R.id.points)
        topNews = View.inflate(activity, R.layout.top_news, null)
        youlikeNews = View.inflate(activity, R.layout.you_like_news, null)
        freelifeNews = View.inflate(activity, R.layout.free_life_news, null)
        listviewtop = topNews?.findViewById(R.id.topNes_list)
        listviewyoulike = youlikeNews?.findViewById(R.id.youlikeNes_list)
        listviewfreelife = freelifeNews?.findViewById(R.id.freelifeNes_list)
        recyclerview.addHeaderView(headBanner)
        recyclerview.addHeaderView(headServices)
        recyclerview.addHeaderView(topNews)
        recyclerview.addHeaderView(youlikeNews)
        recyclerview.addHeaderView(freelifeNews)
        //加载服务产品
//        initProductData()
//        loadbanners()
        proName.clear()
        proUrl.clear()
        proType.clear()
        proIcon.clear()
        proId.clear()
        recyclerview.refresh()
        localDatas = PreferencesUtil(activity)
        getContent()
        listviewtop!!.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val intent = Intent()
            intent.putExtra("title", topentitylist.get(position).title)
            intent.putExtra("url", topentitylist.get(position).url)
            intent.putExtra("id", topentitylist.get(position).content_id)
            intent.putExtra("model", topentitylist.get(position).model_name)
            intent.setClass(activity, WebViewActivity::class.java)
            startActivity(intent)
        }
        listviewyoulike!!.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val intent = Intent()
            intent.putExtra("title", youlikeentitylist.get(position).title)
            intent.putExtra("url", youlikeentitylist.get(position).url)
            intent.putExtra("id", youlikeentitylist.get(position).content_id)
            intent.putExtra("model", youlikeentitylist.get(position).model_name)
            intent.setClass(activity, WebViewActivity::class.java)
            startActivity(intent)
        }
        listviewfreelife!!.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val intent = Intent()
            intent.putExtra("title", freelifeentitylist.get(position).title)
            intent.putExtra("url", freelifeentitylist.get(position).url)
            intent.putExtra("id", freelifeentitylist.get(position).content_id)
            intent.putExtra("model", freelifeentitylist.get(position).model_name)
            intent.setClass(activity, WebViewActivity::class.java)
            startActivity(intent)
        }

    }

    private fun switchActionAndLoadData(action: Int) {
        mCurrentAction = action
        when (mCurrentAction) {
            ACTION_REFRESH -> {
                newsAdapter.clear()
                mCurrentPageIndex = 1
            }
            ACTION_LOAD_MORE -> mCurrentPageIndex++
        }
//        loadNews()
    }

    override fun onResume() {
        super.onResume()
//        getContent()
    }

    private fun initProductData() {
        indicatorLayout!!.removeAllViews()
        listDatas = ArrayList()
        for (i in 0 until proName!!.size) {
            listDatas.add(ProdctBean(proIcon[i], proName[i], proUrl[i]))
        }
        //总的页数向上取整
        totalPage = Math.ceil(listDatas.size * 1.0 / mPageSize).toInt()
        viewPagerList = ArrayList()
        for (i in 0 until totalPage) {
            //每个页面都是inflate出一个新实例
            val gridView: GridView = View.inflate(activity, R.layout.grid_view_layout, null) as GridView
            gridView.adapter = GridViewAdpter(activity, listDatas, i, mPageSize)
            gridView.setOnItemClickListener { _, _, i, _ ->
                val product: ProdctBean = gridView.getItemAtPosition(i) as ProdctBean
                val intent = Intent()
                intent.putExtra("title", product.name)
                intent.putExtra("url", product.url)
                intent.putExtra("id", "")
//                intent.setClass(activity, WebViewActivity::class.java)
//                startActivity(intent)
                if (product.name == "广电直播") {
                    intent.setClass(activity, LivePlayActivity::class.java)
                    startActivity(intent)
                } else {
                    intent.setClass(activity, WebViewActivity::class.java)
                    startActivity(intent)
                }

//                toast(product.name)
//
            }
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView)
        }

        //设置ViewPager适配器
        viewPager!!.adapter = GridViewPagerAdapter(viewPagerList)
        pageItemWidth = ScreenUtils.dip2px(context, mIndicatorWidth.toFloat())

        //添加指示器
        for (i in 0 until totalPage) {
            val view = View(context)
            if (i == 0) {
                view.isPressed = true
                //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ScreenUtils.dip2px(context, 3), pageItemWidth + ScreenUtils.dip2px(context, 3));
                val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                params.setMargins(pageItemWidth, 0, 0, 0)
                view.layoutParams = params
                view.setBackgroundResource(mSelectIndicatorRes)
            } else {
                val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                params.setMargins(pageItemWidth, 0, 0, 0)
                view.layoutParams = params
                view.setBackgroundResource(mUnSelectIndicatorRes)
            }

            indicatorLayout!!.addView(view)
        }

        //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
        viewPager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                val count = indicatorLayout!!.childCount
                for (i in 0 until count) {
                    val view = indicatorLayout!!.getChildAt(i)
                    if (i == position) {
                        view.isPressed = true
                        //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ScreenUtils.dip2px(context, 3), pageItemWidth + ScreenUtils.dip2px(context, 3));
                        val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                        params.setMargins(pageItemWidth, 0, 0, 0)
                        view.layoutParams = params
                        view.setBackgroundResource(mSelectIndicatorRes)
                    } else {
                        val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                        params.setMargins(pageItemWidth, 0, 0, 0)
                        view.layoutParams = params
                        view.setBackgroundResource(mUnSelectIndicatorRes)
                    }
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        banner!!.clearImageTimerTask()
    }

    private fun getContent() {
        topentitylist.clear()
        youlikeentitylist.clear()
        freelifeentitylist.clear()
        val devicesId = Settings.System.getString(activity!!.getContentResolver(), Settings.System.ANDROID_ID)
        OkGo.get<String>(Global.baseUrl + "v1/channel/content")
                .tag(activity)
                .params("channel_id", channelPosition)
                .params("device_code", devicesId)
                .params("user_id", localDatas!!.preferences["user_id"])
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val content = response!!.body()
                        val status = JsonUtil.get_key_string("status", content!!)
                        val msg = JsonUtil.get_key_string("msg", content!!)
                        val code = JsonUtil.get_key_string("code", content!!)
                        val data = JsonUtil.get_key_string("data", content!!)
                        if (status == "0") {
                            var banners1: MutableList<Banner>
                            banners1 = ArrayList()
                            val banners = JsonUtil.getList("banner", data)
                            for (i in 0..banners.size - 1) {
                                var img = JsonUtil.get_key_string("img", banners[i])
                                var url = JsonUtil.get_key_string("url", banners[i])
                                var name = JsonUtil.get_key_string("title", banners[i])
                                var bannerBean = Banner(i, name, img, url)
                                banners1.add(bannerBean)
                            }
                            banner!!.setAdapter(NewsBannerAdapter(activity), banners1 as List<Any>?)
                            var services = JsonUtil.getList("service", data)
                            proName.clear()
                            proUrl.clear()
                            proType.clear()
                            proIcon.clear()
                            proId.clear()
                            for (k in 0..services.size - 1) {
                                var service_id = JsonUtil.get_key_string("service_id", services[k])
                                var name = JsonUtil.get_key_string("name", services[k])
                                var icon = JsonUtil.get_key_string("icon", services[k])
                                var type = JsonUtil.get_key_string("type", services[k])
                                var url = JsonUtil.get_key_string("url", services[k])
                                if (name != "便民服务中心") {
                                    proName.add(name)
                                    proIcon.add(icon)
                                    proId.add(service_id)
                                    proType.add(type)
                                    proUrl.add(url)
                                }

                            }
                            runtimes++
                            initProductData()
                            var top = JsonUtil.getList("top", data)
                            for (n in 0..top.size - 1) {
                                var content_id = JsonUtil.get_key_string("content_id", top[n])
                                var title = JsonUtil.get_key_string("title", top[n])
                                var author = JsonUtil.get_key_string("author", top[n])
                                var thumb_img = JsonUtil.get_key_string("thumb_img", top[n])
                                var url = JsonUtil.get_key_string("url", top[n])
                                var readcount = JsonUtil.get_key_string("readcount", top[n])
                                var model_name = JsonUtil.get_key_string("model_name", top[n])
                                var pub_time = JsonUtil.get_key_string("pub_time", top[n]).toLong()
                                var topentity = TopNewsEntity(content_id, title, author, thumb_img, url, pub_time, readcount, model_name)
                                topentitylist.add(topentity)
                            }
                            listAdapter = TopNewAdapter(context, topentitylist)
                            listviewtop!!.adapter = listAdapter
//                            var youlikeentitylist: MutableList<TopNewsEntity>
//                            youlikeentitylist = ArrayList()
                            var youlike = JsonUtil.getList("like", data)
                            for (m in 0..youlike.size - 1) {
                                var content_id = JsonUtil.get_key_string("content_id", youlike[m])
                                var title = JsonUtil.get_key_string("title", youlike[m])
                                var author = JsonUtil.get_key_string("author", youlike[m])
                                var thumb_img = JsonUtil.get_key_string("thumb_img", youlike[m])
                                var url = JsonUtil.get_key_string("url", youlike[m])
                                var readcount = JsonUtil.get_key_string("readcount", youlike[m])
                                var model_name = JsonUtil.get_key_string("model_name", youlike[m])
                                var pub_time = JsonUtil.get_key_string("pub_time", youlike[m]).toLong()
                                var youlikeentity = TopNewsEntity(content_id, title, author, thumb_img, url, pub_time, readcount, model_name)
                                youlikeentitylist.add(youlikeentity)
                            }
                            listAdapter = TopNewAdapter(context, youlikeentitylist)
                            listviewyoulike!!.adapter = listAdapter
//                            var freelifeentitylist: MutableList<TopNewsEntity>
//                            freelifeentitylist = ArrayList()
                            var freelife = JsonUtil.getList("life", data)
                            for (l in 0..freelife.size - 1) {
                                var content_id = JsonUtil.get_key_string("content_id", freelife[l])
                                var title = JsonUtil.get_key_string("title", freelife[l])
                                var author = JsonUtil.get_key_string("author", freelife[l])
                                var thumb_img = JsonUtil.get_key_string("thumb_img", freelife[l])
                                var url = JsonUtil.get_key_string("url", freelife[l])
                                var readcount = JsonUtil.get_key_string("readcount", freelife[l])
                                var model_name = JsonUtil.get_key_string("model_name", freelife[l])
                                var pub_time = JsonUtil.get_key_string("pub_time", freelife[l]).toLong()
                                var freelifeentity = TopNewsEntity(content_id, title, author, thumb_img, url, pub_time, readcount, model_name)
                                freelifeentitylist.add(freelifeentity)
                            }
                            listAdapter = TopNewAdapter(context, freelifeentitylist)
                            listviewfreelife!!.adapter = listAdapter
                            recyclerview.refreshComplete()
                            recyclerview.setLoadingListener(object : XRecyclerView.LoadingListener {
                                override fun onRefresh() {
                                    getContent()
                                }

                                override fun onLoadMore() {
                                    switchActionAndLoadData(ACTION_LOAD_MORE)
                                }
                            })

                        } else {
                            toast(getString(R.string.readFaile))
                        }
                    }

                })

    }
}
